/* 权限函数工具库
 * author hua
 * 2018,3,29
 */
import mui from 'static/js/mui'
import router from '../router/index'

/* 获取token
 * params:tokenName;令牌名
 * params:expirationTime;过期时间
 * return bool or token
 */
export function getToken (tokenName, expirationTime) {
  let data = window.localStorage.getItem(tokenName)
  if (data == null) {
    return false
  }
  let dataObj = JSON.parse(data)
  if ((new Date().getTime() - dataObj.time) > parseInt(expirationTime)) {
    // window.localStorage.clear()
    localStorage.removeItem(tokenName)
    mui.alert('账号过期', '信息框', ['确定'], function () {
      // document.location.href = 'http://www.baidu.com'
      router.go({ name: 'login' })
    }, 'div')
    return false
  } else {
    var dataObjDatatoJson = dataObj.data
    return dataObjDatatoJson
  }
}

/* 设置token
 * params:tokenName;令牌名
 * params:tokenVal;令牌值
 * return bool
 */
export function setToken (tokenName, tokenVal) {
  let curTime = new Date().getTime()
  window.localStorage.setItem(tokenName, JSON.stringify({ data: tokenVal, time: curTime }))
  return true
}

/* 销毁token
 * params:tokenName;令牌名
 * return bool
 */
export function removeToken (tokenName) {
  localStorage.removeItem(tokenName)
  return true
}

/* base64再次根据字典进行替换加密
 * params: data;json数据
 */
export function base64Encode (data) {
  const dict = {
    'Y': '\x1a',
    'L': '\r',
    'V': '\x17',
    'S': '\x14',
    'C': '\x04',
    'I': '\n',
    'T': '\x15',
    'M': '\x0e',
    'Z': '\x1b',
    'X': '\x19',
    'N': '\x0f',
    'H': '\t',
    'A': '\x02',
    'D': '\x05',
    'R': '\x13',
    'E': '\x06',
    'O': '\x10',
    'Q': '\x12',
    'G': '\x08',
    'W': '\x18',
    'P': '\x11',
    'J': '\x0b',
    'B': '\x03',
    'F': '\x07',
    'K': '\x0c',
    'U': '\x16'
  }
  // //console.log(JSON.stringify(data))
  // base64加密
  let Base64 = require('js-base64').Base64
  let strData = Base64.encode(JSON.stringify(data))
  // 替换
  for (let key in dict) {
    strData = strData.replace(key, dict[key])
  }
  ////console.log(strData)
  return strData
}
